//
//  ZYOauthController.swift
//  MyWeiBo
//
//  Created by 牛牛很牛 on 15/12/18.
//  Copyright © 2015年 曾勇召. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZYOauthController: UIViewController,UIWebViewDelegate {
    override func loadView() {
        //在这个里面不需要添加约束
        view = webView
        webView.delegate = self
    }
    
 //实现webView的代理方法
    //开始加载时显示加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    //加载完毕后，加载画面消失，关闭指示器
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //webView是否要去加载一个网址，返回true加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL!.absoluteString
        // url  https://api.weibo.com/oauth2/authorize?client_id=954617978&redirect_uri=http://www.baidu.com
        //授权界面  https://api.weibo.com/oauth2/authorize
        //点击取消后  http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        //点击授权后  http://www.baidu.com/?code=6d9ee9e7a0f2f4f536a611e99cb2d579
        
        //只有点击 取消或授权,才会加载 授权回调地址,其他情况不会加载授权回调地址
        // 不是授权回调地址(登录地址),直接加载
        if !url.hasPrefix(ZYZNetworkTool.shareNetworkTool1.redirect_uri){
            return true
        }
        
        //来到这里，就表示点击了授权或点击按钮，就不让他加载网页，只是获取code而已。
        if let query = request.URL?.query {
            //来到这里，表示query有值  query:code=5fa0dd50be2f5d47783d21b8a5be2093
            if query.hasPrefix("code="){
                let queryNS = query as NSString
                let code = queryNS.substringFromIndex("code=".characters.count)
                //调用当前类的loadaccessToken方法
                loadAccessToken(code)
                print(query)
                
                print(code)
                
                
            
            }else //没有获取到code就关闭。
            {
                self.close()
            }
        
        }

        return false
    }
    
    //控制器加载AccessToken
    func loadAccessToken(code:String) {
        // .调用网络工具类加载AccessToken,准备好了一个闭包
        ZYZNetworkTool.shareNetworkTool1.loadAccesToken(code) { (result, error) -> () in
            if error != nil && result == nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Black)
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                    // 关闭授权控制器
                    self.close()
                })
            return
            }
            
            //到这来没有错误，可以加载accessToken,保存到模型里
           // print(result)
            let userAcount = ZYZUserAcount(dict: result!)
            print("U: \(userAcount)")
            
            //保存到沙盒里
            userAcount.saveUserAccount()
            
            
            //  切换控制器,到HomeViewController
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
           
            self.close()
        }
    
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        //加载新浪的weib写的登陆界面
        let url = ZYZNetworkTool.shareNetworkTool1.oauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        //设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    //填充,在web里改脚本语言自动填充账号和密码
    func autoFill(){
        let js = "document.getElementById('userId').value='13627267965'; document.getElementById('passwd').value='z4441423';"
       webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //取消
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true) { (_) -> Void in
        }
    }
    

    
    // MARK: - 懒加载
    private lazy var webView = UIWebView()

}
